import logging
import traceback
from functools import wraps

from flask import make_response,Flask, jsonify, json, request, session, send_file, Blueprint, abort
from flask_cors import CORS
import math
import time
import os
import copy
import requests
from datetime import timedelta
import xlrd
from apps.tools.register import *
from apps.db import *

CORS(app, resources=r'/*')

app.debug = True
app.SEND_FILE_MAX_AGE_DEFAULT = timedelta(seconds=1)
app.secret_key = 'locus'

# 获取当前环境
environment = os.environ.get('ENVIRONMENT')

print(environment)


def to_dict_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if isinstance(result, Result):
            return result.to_dict()
        return result

    return wrapper


def register_routes(app, folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith('.py'):
                module_name = os.path.splitext(file)[0]
                module_path = os.path.join(root, file).replace(os.sep, '.')
                module_path = module_path.replace('.py', '')
                module_path = module_path.replace('/', '.')
                module = __import__(module_path, fromlist=['routes'])
                if hasattr(module, 'routes'):
                    blueprint = Blueprint(module_name, __name__)
                    blueprint.url_prefix = '/'
                    module.routes(blueprint)
                    app.register_blueprint(blueprint, url_prefix=blueprint.url_prefix)


register_routes(app, 'apps/controller')

# @app.after_request
# def af_req(resp):  # 解决跨域session丢失
#     resp = make_response(resp)
#     resp.headers['Access-Control-Allow-Origin'] = HOST_1
#     resp.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS'
#     # resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
#     resp.headers[
#         'Access-Control-Allow-Headers'] = 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
#     resp.headers['Access-Control-Allow-Credentials'] = 'true'
#     resp.headers['X-Powered-By'] = '3.2.1'
#     resp.headers['Content-Type'] = 'application/json;charset=utf-8'
#     return resp


if __name__ == '__main__':
    # s3_client = S3Operation()
    app.run(debug=True, threaded=True, host=HOST_2, port=PORT)
    # app.run()
